var datasets={};
var plots={};
var options;
var plot;
function loadPage(){
	
	$("#content").hide();
	//timestamp are using client gmt
	options = {
			series: { shadowSize: 0 },
			legend:{
		       show:false
	        },
	        xaxis: {  tickFormatter: function(val){ 
		         var d = new Date(val); 
		         return getDay(d) + "/" +getMonth(d)+" "+ getHour(d)+":"+getMinute(d); 
	        }}
	  };
	 
	 jQuery.ajax( {
			type : "GET",
			url : "load_main",
			dataType : "json",
			async : true,
			success : function(json) {
			
		 	  $("#footer").html(parseTemplate("graph_right", {
					json : json["data"]
			  }));
		 	 
		      for(prop in json["data"]){
		    	  var i = 0;//prevent shifting color
			      $.each(json["data"][prop]["dataset"], function(key, val) {
			          val.color = i;
			          ++i;
			      });
			      datasets[prop]=json["data"][prop]["dataset"];
			      
			      jQuery("#codeCache_"+prop).bind("click", { param: prop },legendItemClick);
			      
			      jQuery("#codeCachem_"+prop).bind("click", { param: prop },legendItemClick);
			  	
				  jQuery("#edenSpace_"+prop).bind("click", { param: prop },legendItemClick);
				  	
				  jQuery("#edenSpacem_"+prop).bind("click", { param: prop },legendItemClick);
				  	
				  jQuery("#survivorSpace_"+prop).bind("click", { param: prop },legendItemClick);
				  	
				  jQuery("#survivorSpacem_"+prop).bind("click", { param: prop },legendItemClick);
				  	
				  jQuery("#oldGenSpace_"+prop).bind("click", { param: prop },legendItemClick);
				  	
				  jQuery("#oldGenSpacem_"+prop).bind("click", { param: prop },legendItemClick);
				  	
				  jQuery("#permGenSpace_"+prop).bind("click", { param: prop },legendItemClick);
				  
				  jQuery("#permGenSpacem_"+prop).bind("click", { param: prop},legendItemClick);
			  		
		      }
		      
		      plotAccordingToChoices();
		      
			}
		});
	 update();
}

function plotAccordingToChoices() {
	
	  var plot;
	  for(prop in datasets){
		  var datas=datasets[prop];
		  var data=[];
		  for(key in datas){
			  data.push(datas[key]);
		  }
		  plot=$.plot($("#placeholder_"+prop),data , options);
		  plots[""+prop]=plot;
	  }
     
}

function update() {
	
	 jQuery.ajax( {
			type : "GET",
			url : "load_main",
			dataType : "json",
			async : true,
			success : function(json) {
		 
		 var plot;
		 for(prop in json["data"]){
	  
			 var i=0;
			 $.each(json["data"][prop]["dataset"], function(key, val) {
				 val.color = i;
				 ++i;
			 });
			  var datas=datasets[prop]=json["data"][prop]["dataset"];
		      var data=[];
			  var choiceContainer = $("#jboss_instance_"+prop);
			    choiceContainer.find("input:checked").each(function () {
			        var key = $(this).attr("name");
			        if (key && datas[key])
			            data.push(datas[key]);
			    });
			    plot=plots[""+prop];
			    plot.setData(data);
			    plot.setupGrid();
		        plot.draw();
			   //$.plot($("#placeholder_"+prop),data , options);
		 }
		}
		});
    
    setTimeout(update,10000);
}

function legendItemClick(event) {
	
	var instanceId=event.data.param
    var data = [];
    var datas=datasets[instanceId];
    var choiceContainer = $("#jboss_instance_"+instanceId);
    choiceContainer.find("input:checked").each(function () {
        var key = $(this).attr("name");
        if (key && datas[key])
            data.push(datas[key]);
    });
    if (data.length > 0){
    	$.plot($("#placeholder_"+instanceId),data , options);
    }
       
    
}

function clearReportData(instanceId){
	
	var answer = confirm ("This will delete all data.Are you sure?");
	
	if (answer)
		$.ajax( {
			type :'POST',
			url :'delete_reports',
			data : {
				instanceId :instanceId
			},
			dataType :'json',
			success :function(json) {
				if(json=='OK'){
					
					loadPage();
					
				}else{
					
				    alert("Error while clearing data");
				    
				}
			}
		});		
}

function exportData(instanceId){
	alert("girildi");
	$.ajax( {
		type :'GET',
		url :'export_reports',
		data : {
			instanceId :instanceId
		},
		//dataType :'json',
		success :function(json) {
			
			
		}
	});
}

function getHour(d) {
	var date = d.getHours();
	if (date < 10)
		return "0" + date.toString();
	else
		return date.toString();
}

function getMinute(d) {
	var date = d.getMinutes();
	if (date < 10)
		return "0" + date.toString();
	else
		return date.toString();
}

function getMonth(d) {
	var date = d.getMonth()+1;
	if (date < 10)
		return "0" + date.toString();
	else
		return date.toString();
}

function getDay(d) {
	var date = d.getDate();
	if (date < 10)
		return "0" + date.toString();
	else
		return date.toString();
}
var _tmplCache = {};

/**
 * $("#dyncontent").html(parseTemplate("list", {
				json : json
			}));
 */
function parseTemplate(templateId, data) {

	var err = "";
	var str = '';
	var func;
	$
			.ajax( {
				type : "GET",
				url : "static/"+templateId + ".html",
				async : false,
				success : function(html) {
					str = html;
					try {
						func = _tmplCache[str];
						if (!func) {
							var strFunc = "var p=[],print=function(){p.push.apply(p,arguments);};"
									+ "with(obj){p.push('"
									+ str.replace(/[\r\t\n]/g, " ").replace(
											/'(?=[^#]*#>)/g, "\t").split("'")
											.join("\\'").split("\t").join("'")
											.replace(/<#=(.+?)#>/g, "',$1,'")
											.split("<#").join("');")
											.split("#>").join("p.push('")
									+ "');}return p.join('');";
							func = new Function("obj", strFunc);
							_tmplCache[str] = func;
						}

					} catch (e) {
						err = e.message;
						return "< # ERROR: " + err + " # >";
					}
				}
			});
	return func(data);
};

$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = $.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});